import 'package:audio_session/audio_session.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';

import 'logger.dart';

class AudioRecordManager {
  FlutterSoundRecorder? _audioRecorder;
  bool _isRecording = false;

  Future<bool> hasPermission() async {
    var status = await Permission.microphone.status;
    return status == PermissionStatus.granted;
  }

  Future<void> openRecorder() async {
    if (await hasPermission()) {
      _audioRecorder = FlutterSoundRecorder();
      await _audioRecorder?.openRecorder();
      _audioRecorder?.setLogLevel(Level.error);

      final session = await AudioSession.instance;
      await session.configure(
        AudioSessionConfiguration(
          avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
          avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.allowBluetooth | AVAudioSessionCategoryOptions.defaultToSpeaker,
          avAudioSessionMode: AVAudioSessionMode.spokenAudio,
          avAudioSessionRouteSharingPolicy: AVAudioSessionRouteSharingPolicy.defaultPolicy,
          avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
          androidAudioAttributes: const AndroidAudioAttributes(
            contentType: AndroidAudioContentType.speech,
            flags: AndroidAudioFlags.none,
            usage: AndroidAudioUsage.voiceCommunication,
          ),
          androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
          androidWillPauseWhenDucked: true,
        ),
      );
    } else {
      logger.e("❌没有麦克风权限");
    }
  }

  Future<String?> startRecording() async {
    if (_audioRecorder == null) {
      await openRecorder();
    }
    final directory = await getTemporaryDirectory();
    final filePath = '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.wav';

    await _audioRecorder?.startRecorder(
      toFile: filePath,
      codec: Codec.pcm16WAV,
      audioSource: AudioSource.microphone,
    );
    _isRecording = true;
    return filePath;
  }

  Future<String?> stopRecording() async {
    if (_isRecording) {
      final filePath = await _audioRecorder?.stopRecorder();
      _isRecording = false;
      return filePath;
    } else {
      throw Exception("录音未开始！");
    }
  }

  /// 检查是否正在录音
  bool isRecording() => _isRecording;

  /// 释放资源
  void dispose() {
    _audioRecorder?.closeRecorder();
  }
}
